package ApplicationTest.Example.KafKa.Consumer

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.{HasOffsetRanges, KafkaUtils, OffsetRange}
import org.apache.spark.streaming.{Milliseconds, StreamingContext}

object KafkaConsumer {

  private val conf = new SparkConf().setMaster("local[*]").setAppName("Scala Spark Test Application")

  def main(args: Array[String]): Unit = {
    //key Word Count
    lazy val stream = new StreamingContext(conf, Milliseconds(5000))
    val bootstrapServers = "master:9092,spark02:9092,spark03:9092"

    val groupId = "group1"

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> bootstrapServers, //连接两台kafka 服务 -- 关于zookeeper 发现
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId, //分配一个组
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )


    val topics = Array("helloword").toSet //本地集群决定 topic


    var kafkaStream = KafkaUtils.createDirectStream[String, String](stream, PreferConsistent, Subscribe[String, String](topics, kafkaParams))

    var offsetRanges = Array[OffsetRange]()
    kafkaStream.transform{ rdd =>
      offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges
      rdd
    }.foreachRDD{
      rdd =>
        rdd.foreachPartition(
          partition => partition.foreach{ //每一个分区
            rdd =>
              val time = rdd.timestamp() //时间戳
              val key = rdd.key()
              val value = rdd.value()
              val partition = rdd.partition()
              val offset = rdd.offset()
              val topic = rdd.topic()
              println(s"$time - $key - $value - $partition - $offset - $topic")
          }
        )
    }

    stream.start()
    stream.awaitTermination()
  }
}
